<template>
  <el-form :inline="true" class="demo-form-inline" :model="cForm" :disabled="!isShowList">
    <el-form-item label="一级分类" >
      <el-select placeholder="请选择" v-model="cForm.category1Id" @change="handlerCategory1">
        <el-option :label="c1.name" :value="c1.id" v-for="(c1,index) in category1List" :key="c1.id"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="二级分类">
      <el-select placeholder="请选择" v-model="cForm.category2Id" @change="handlerCategory2">
        <el-option :label="c2.name" :value="c2.id" v-for="(c2,index) in category2List" :key="c2.id"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="三级分类">
      <el-select placeholder="请选择" v-model="cForm.category3Id" @change="handlerCategory3">
        <el-option :label="c3.name" :value="c3.id" v-for="(c3,index) in category3List" :key="c3.id"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script>

export default {
  name: "CategroySelector",
  data() {
    return {
      cForm:{
        category1Id:'',
        category2Id:'',
        category3Id:''
      },
      category1List:[],
      category2List:[],
      category3List:[]
    }
  },
  props:['isShowList'],
  mounted() {
    this.getCategory1List()
  },
  methods:{
    // 获取一级表单
    async getCategory1List(){
      try {
        const result = await this.$API.category.getCategory1()
        if(result.code === 200 || result.code === 20000){
          this.category1List = result.data
        }
      } catch (error) {
        this.$message.error('一级表单获取是失败'+error.message)
      }
    },
    // 点击一级分类的时候的回调获取二级分类
    async handlerCategory1(category1Id){
      // 切换一级分类清空二三级列表
      this.cForm.category2Id = ''
      this.cForm.category3Id = ''
      this.category2List = []
      this.category3List = []
      // 给父组件传递数据
      this.$emit('changeCategory',{categoryId:category1Id,level:1})
      try {
        const result = await this.$API.category.getCategory2(category1Id)
        if (result.code === 200 || result.code === 20000) {
          this.category2List = result.data
        }
      } catch (error) {
        this.$message.error('二级表单获取失败'+error.message)
      }
    },
  // 点击二级分类的时候的回调获取三级分类
  async handlerCategory2(category2Id){
    // 切换二级分类清空三级列表
    this.cForm.category3Id = ''
    this.category3List = []

    // 给父组件传递数据
    this.$emit('changeCategory',{categoryId:category2Id,level:2})
    try {
        const result = await this.$API.category.getCategory3(category2Id)
        if (result.code === 200 || result.code === 20000) {
          this.category3List = result.data
        }
      } catch (error) {
        this.$message.error('三级表单获取失败'+error.message)
      }
    },
  // 点击三级分类时,传递数据
  handlerCategory3(category3Id){
    // 给父组件传递数据
    this.$emit('changeCategory',{categoryId:category3Id,level:3})
    }
  },
};
</script>

<style>
</style>
